import Vue from 'vue'
// 导入vuex插件
import Vuex from 'vuex'

//声明vue需要使用 vuex插件
Vue.use(Vuex)

export default new Vuex.Store({
  //state用于存放状态数据
  state: {
    loginName:'',
    isLogin:false,
    shopCartItems:[
        { id: 101, name: "汽车", price: 99999, num: 1 },
        { id: 102, name: "电视", price: 1999, num: 1 },
        { id: 103, name: "笔记本电脑", price: 7888, num: 1 },
        { id: 104, name: "洗衣机", price: 2888, num: 1 },
        { id: 105, name: "电熨斗", price: 199, num: 1 }
    ]
  },
  //用来修改state中的数据
  mutations: {
    addToShopCart(state,item){
      state.shopCartItems.push(item)
    },
    loginIn:function(state,loginName){
      state.loginName = loginName
      state.isLogin = true
    },
    loginOut(state){
      state.loginName = ''
      state.isLogin = false
    }
  },
  getters:{
    //购物车中商品数量
    count: state => {
      return state.shopCartItems.length
    },
    //购物车中商品总价格
    totalPrice: state => {
      var totalPrice = 0
      state.shopCartItems.forEach(shopCart => {
      // state.shopCartItems.forEach(function(shopCart){
          totalPrice = totalPrice + shopCart.num * shopCart.price
      })
      return totalPrice
    }
  },
  actions: {
  },
  modules: {
  }
})
